package org.cainiao.portal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.cainiao.portal.dao.service.KnowledgeAreaMapperService;
import org.cainiao.portal.dto.response.knowledge.ChartTreeNode;
import org.cainiao.portal.entity.knowledge.KnowledgeArea;
import org.cainiao.portal.service.KnowledgeAreaService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@Service
@RequiredArgsConstructor
public class KnowledgeAreaServiceImpl implements KnowledgeAreaService {

    private final KnowledgeAreaMapperService knowledgeAreaMapperService;

    @Override
    public IPage<KnowledgeArea> knowledgeAreaPage(int current, int size, String key) {
        return knowledgeAreaMapperService.searchPage(current, size, key);
    }

    @Override
    public List<ChartTreeNode> publishedKnowledgeAreaChart() {
        List<KnowledgeArea> knowledgeAreas = knowledgeAreaMapperService.findByPublished(true);

        Map<Long, ChartTreeNode> idKnowledgeAreaMap = new HashMap<>();
        for (KnowledgeArea knowledgeArea : knowledgeAreas) {
            idKnowledgeAreaMap.put(knowledgeArea.getId(), ChartTreeNode.builder()
                .id(knowledgeArea.getId()).name(knowledgeArea.getName()).value(1).build());
        }

        List<ChartTreeNode> roots = new ArrayList<>();
        for (KnowledgeArea knowledgeArea : knowledgeAreas) {
            ChartTreeNode chartTreeNode = idKnowledgeAreaMap.get(knowledgeArea.getId());
            Long parentId = knowledgeArea.getParentId();
            if (parentId == null) {
                roots.add(chartTreeNode);
            } else {
                ChartTreeNode parent = idKnowledgeAreaMap.get(parentId);
                if (parent == null) {
                    roots.add(chartTreeNode);
                } else {
                    List<ChartTreeNode> children = parent.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        children.add(chartTreeNode);
                        parent.setChildren(children);
                        parent.setValue(null);
                    } else {
                        children.add(chartTreeNode);
                    }
                }
            }
        }
        return roots;
    }
}
